package com.gylang.im.core.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gylang.commons.dto.BaseDTO;
import com.gylang.mapper.domain.BaseDO;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * @author gylang
 * data 2020/11/25
 * @version v0.0.1
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO, D extends BaseDTO>
        extends ServiceImpl<M, T> implements BaseService<T, D> {

    private final IConverter<D, T> converter;

    public BaseServiceImpl(IConverter<D, T> converter) {
        this.converter = converter;
    }

    @Override
    public D findOne(D d) {
        T t = converter.converterDO(d);
        T result = getOne(new QueryWrapper<T>(t));
        if (null != result) {
            return converter.converterDTO(t);
        } else {
            return null;
        }
    }

    @Override
    public List<D> selectList(D d) {

        T t = converter.converterDO(d);
        List<T> result = list(new QueryWrapper<T>(t));
        return converter.converterDTOList(result);
    }

    @Override
    public boolean save(D dto) {
        return save(converter.converterDO(dto));
    }

    @Override
    public boolean insertBatch(Collection<D> entityList) {

        return saveBatch(converter.converterDOList(entityList));
    }

    @Override
    public boolean insertBatch(Collection<D> entityList, int batchSize) {
        return saveBatch(converter.converterDOList(entityList), batchSize);
    }

    @Override
    public boolean insertOrUpdateBatch(Collection<D> entityList) {
        return saveOrUpdateBatch(converter.converterDOList(entityList));
    }

    @Override
    public boolean insertOrUpdateBatch(Collection<D> entityList, int batchSize) {
        return saveOrUpdateBatch(converter.converterDOList(entityList), batchSize);
    }

    @Override
    public boolean updateById(D entity) {
        return updateById(converter.converterDO(entity));
    }

    @Override
    public boolean updateBatch(Collection<D> entityList) {
        return updateBatchById(converter.converterDOList(entityList));
    }

    @Override
    public boolean updateBatch(Collection<D> entityList, int batchSize) {
        return updateBatchById(converter.converterDOList(entityList), batchSize);
    }

    @Override
    public boolean saveOrUpdate(D entity) {
        return saveOrUpdate(converter.converterDO(entity));
    }

    @Override
    public D findById(Serializable id) {
        return converter.converterDTO(getById(id));
    }

    @Override
    public List<D> findByIds(Collection<? extends Serializable> idList) {
        return converter.converterDTOList(listByIds(idList));
    }


}
